// 权限检查工具
import { getToken } from './api';

// 获取用户信息
export const getUserInfo = () => {
  return wx.getStorageSync('userInfo');
};

// 获取当前用户ID
export const getCurrentUserId = (): number | null => {
  const userInfo = getUserInfo();
  return userInfo?.id || null;
};

// 设置用户信息
export const setUserInfo = (userInfo: any) => {
  wx.setStorageSync('userInfo', userInfo);
};

// 移除用户信息
export const removeUserInfo = () => {
  wx.removeStorageSync('userInfo');
};

// 清除所有用户相关数据
export const clearUserData = () => {
  wx.removeStorageSync('token');
  wx.removeStorageSync('refreshToken');
  wx.removeStorageSync('userInfo');
};

/**
 * 检查用户是否已登录
 */
export const isLoggedIn = (): boolean => {
  return !!getToken();
};

/**
 * 路由守卫 - 检查登录状态
 * 如果未登录，跳转到登录页
 */
export const requireAuth = (): boolean => {
  const loggedIn = isLoggedIn();
  if (!loggedIn) {
    wx.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 1500,
    });
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/login/index',
      });
    }, 1500);
  }
  return loggedIn;
};

/**
 * 路由守卫 - 检查登录状态并执行回调
 */
export const withAuth = (callback: () => void): void => {
  if (isLoggedIn()) {
    callback();
  } else {
    wx.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 1500,
    });
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/login/index',
      });
    }, 1500);
  }
};

/**
 * 检查是否是当前用户的记录
 */
export const isCurrentUserRecord = (recordUserId: number, currentUserId?: number): boolean => {
  // 这里需要根据实际用户ID比较逻辑实现
  // 暂时返回false，需要在实际使用时传入当前用户ID
  return false;
};

/**
 * 权限不足提示
 */
export const showPermissionDenied = (message: string = '权限不足'): void => {
  wx.showToast({
    title: message,
    icon: 'none',
    duration: 2000,
  });
};

export default {
  isLoggedIn,
  requireAuth,
  withAuth,
  isCurrentUserRecord,
  showPermissionDenied,
  getUserInfo,
  getCurrentUserId,
  setUserInfo,
  removeUserInfo,
  clearUserData,
};
